package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import bean.LoggedUser;
import bean.Model;
import bean.User;
import bean.UserType;
import dao.LoginDAO;
import dao.UserDAO;
import formBean.LoginForm;

public class LoginAction extends Action {

	private FormBeanFactory<LoginForm> formBeanFactory = FormBeanFactory.getInstance(LoginForm.class);
	
	private LoginDAO loginDAO;
	private UserDAO userDAO;
	
	public LoginAction(Model model)
	{
		loginDAO = model.getLoginDAO();
		userDAO = model.getUserDAO();
	}
	
	@Override
	public String getName() {
		return "login.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		// TODO Auto-generated method stub
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
		try {
			LoginForm form = formBeanFactory.create(request);
			HttpSession session = request.getSession(false);
			request.setAttribute("form", form);
			if (!form.isPresent()) {
				LoggedUser user = (LoggedUser)session.getAttribute("user");
				if(user != null)
				{
			        
			        session.setAttribute("user",null);
			        session.invalidate();
					request.getSession().setAttribute("user", null);
				}
	            return "login.jsp";
	        }
			errors.addAll(form.getValidationErrors());
			if(errors.size()>0)
			{
				return "login.jsp";
			}
			else
			{
				User dbUser = userDAO.lookUpByUsername(form.getUserName());
				LoggedUser user = null;
//				LoggedUser user = loginDAO.getUserByName(form.getUserName());
				if(dbUser!= null)
				{
					user = loginDAO.loginUser(dbUser);
					if(!user.getPassword().equals(form.getPassword()) && !DigestUtils.md5Hex(user.getPassword()).equals(form.getPassword()))
					{
						errors.add("Password Wrong!");
					}
				}
				else
				{
					errors.add("Invalid user");
				}
				
				if(errors.size()>0)
				{
					return "login.jsp";
				}
				else
				{
					session.setAttribute("user", user);
					if(user.getUserType().equals(UserType.Employee))
					{
						request.setAttribute("message", "Welcome back!");
					}
					return util.Util.getDefaultPage(user.getUserType(), request);
				}
			}
		} catch (FormBeanException e) {
			e.printStackTrace();
			return "error.jsp";
		}
	}

	@Override
	public UserType getType() {
		return UserType.Both;
	}

}
